﻿/**
 * Copyright © 2002 Matt Griffith
 * Copyright © 2004-09 Michael Flanakin
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the 
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the 
 * Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 
 * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
using System;
using System.IO;
using System.Text;

namespace UpdateVersion
{
	internal class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static int Main(string[] args)
		{
			// init vars
			Options options;
			string input;
			VersionUpdater updater;

			// parse the command line
			try
			{
				options = new Options(args);
			}
			catch(Exception e)
			{
				Console.Error.WriteLine("Error parsing command line options.");
				Console.Error.WriteLine(e);
				Console.Error.WriteLine();
				Console.Error.WriteLine(Options.Usage);
				return 1;
			}

			// get the input
			try
			{
				input = GetInput(options);
			}
			catch(Exception e)
			{
				Console.Error.WriteLine("Error reading input.");
				Console.Error.WriteLine(e);
				return 2;
			}

			// update the version number in the input
			try
			{
				updater = new VersionUpdater(input, options);
			}
			catch(Exception e)
			{
				Console.Error.WriteLine("Error updating version.");
				Console.Error.WriteLine(e);
				return 3;
			}

			// write the output
			try
			{
				WriteOutput(updater, options);
			}
			catch(Exception e)
			{
				Console.Error.WriteLine("Error writing output.");
				Console.Error.WriteLine(e);
				return 4;
			}

			// return normally
			return 0;
		}


		/// <summary>
		/// Private helper method that gets the input string from the appropriate source.
		/// </summary>
		/// <param name="options">The command line options.</param>
		/// <returns>
		/// Returns the input string.
		/// </returns>
		private static string GetInput(Options options)
		{
			// if no input file, get from standard input; otherwise, read file
			return String.IsNullOrEmpty(options.InputFilename) ? Console.In.ReadToEnd() : ReadFile(options.InputFilename);
		}


		/// <summary>
		/// Private helper that reads the input string from a file.
		/// </summary>
		/// <param name="file">The name of the file to read.</param>
		/// <returns>The string representing the data stored in the input file.</returns>
		/// <exception cref="ArgumentNullException"><paramref cref="file"/> is <c>null</c> or empty.</exception>
		/// <exception cref="FileNotFoundException">The <paramref cref="file"/> does not exist.</exception>
		private static string ReadFile(string file)
		{
			// validate prarms
			if (String.IsNullOrEmpty(file))
			{
				throw new ArgumentNullException("file");
			}
			if (!File.Exists(file))
			{
				throw new FileNotFoundException("File does not exist.", "filename");
			}

			// read file
			using (var stream = File.OpenRead(file))
			{
				var reader = new StreamReader(stream, Encoding.Default, true);
				return reader.ReadToEnd();
			}
		}


		/// <summary>
		/// Writes the output string to the appropriate target.
		/// </summary>
		/// <param name="updater">The updater.</param>
		/// <param name="options">The command line options.</param>
		/// <exception cref="ArgumentNullException"><paramref name="updater"/> is <c>null</c>.</exception>
		/// <exception cref="ArgumentException"><paramref name="updater"/> has a <c>null</c> or empty output.</exception>
		private static void WriteOutput(VersionUpdater updater, Options options)
		{
			// validate params
			if (updater == null)
			{
				throw new ArgumentNullException("updater");
			}
			if (String.IsNullOrEmpty(updater.Output))
			{
				throw new ArgumentException("Output is null", "updater");
			}

			if (String.IsNullOrEmpty(options.OutputFilename))
			{
				// output file name not specified; write output to standard output stream
				if (options.WriteNewVersion)
					Console.WriteLine(updater.NewVersion);
				else
					Console.Out.Write(updater.Output);
			}
			else
			{
				// write new version to output stream
				if (options.WriteNewVersion)
					Console.Out.WriteLine(updater.NewVersion);

				// output file specified; write output to specified file
				using(var writer = new StreamWriter(options.OutputFilename, false, Encoding.Default))
				{
					writer.Write(updater.Output);
				}
			}
		}
	}
}